package org.smart4j.chapter3.helper;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.chapter3.service.CustomerService;
import org.smart4j.framework.helper.ConfigHelper;
import org.smart4j.framework.util.CastUtil;
import org.smart4j.framework.util.CollectionUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class DatabaseHelper {

    private static final Logger logger = LoggerFactory.getLogger(CustomerService.class);

    private static final QueryRunner QUERY_RUNNER;

    private static final ThreadLocal<Connection> CONNECTION_HOLDER;

    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;
    private static final BasicDataSource BASIC_DATA_SOURCE;

    static {


        CONNECTION_HOLDER = new ThreadLocal<Connection>();

        //Properties conf = PropsUtil.loadProps("config.properties");
        DRIVER = ConfigHelper.getJdbcDriver();
        URL = ConfigHelper.getJdbcUrl();
        USERNAME = ConfigHelper.getJdbcUsername();
        PASSWORD = ConfigHelper.getJdbcPassword();
        BASIC_DATA_SOURCE = new BasicDataSource();
        BASIC_DATA_SOURCE.setDriverClassName(DRIVER);
        BASIC_DATA_SOURCE.setUrl(URL);
        BASIC_DATA_SOURCE.setUsername(USERNAME);
        BASIC_DATA_SOURCE.setPassword(PASSWORD);
        QUERY_RUNNER = new QueryRunner(BASIC_DATA_SOURCE);
//        try {
//            Class.forName(DRIVER);
//        } catch (ClassNotFoundException e) {
//            logger.error("sql driver load failure",e);
//        }
    }

//    private static Connection getConnection(){
//        Connection conn = CONNECTION_HOLDER.get();
//        if(conn == null) {
//            try {
//                conn = BASIC_DATA_SOURCE.getConnection();
//            } catch (SQLException e) {
//                logger.error("execute sql failure", e);
//                throw new RuntimeException(e);
//            }finally {
//                CONNECTION_HOLDER.set(conn);
//            }
//        }
//        return conn;
//
//    }

//    private static void closeConnection(){
//        Connection conn = CONNECTION_HOLDER.get();
//        if (conn != null){
//            try {
//                conn.close();
//            } catch (SQLException e) {
//                logger.error("close connection failure",e);
//                throw new RuntimeException(e);
//            }finally {
//                CONNECTION_HOLDER.remove();
//            }
//        }
//
//    }

    /**
     * 查询返回列表
     * @param entityClass
     * @param sql
     * @param params
     * @param <T>
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass,String sql, Object... params){
        List<T> entityList;
        try {
            entityList = QUERY_RUNNER.query(sql,new BeanListHandler<T>(entityClass),params);
        }catch (SQLException e){
            logger.error("query entity list failure",e);
            throw new RuntimeException(e);
        }finally {
            //closeConnection();
        }
        return entityList;
    }

    /**
     * 查询返回具体Entity
     * @param entityClass
     * @param sql
     * @param params
     * @param <T>
     * @return
     */
    public static <T> T queryEntity(Class<T> entityClass,String sql,Object... params){
        T entity;
        try {
            entity = QUERY_RUNNER.query(sql,new BeanHandler<T>(entityClass),params);
        } catch (SQLException e) {
           logger.error("query entity failure",e);
           throw new RuntimeException(e);
        }finally {
            //closeConnection();
        }
        return entity;
    }

    /**
     *
     * @param sql
     * @param params
     * @return
     */
    public static List<Map<String,Object>> executeQuery(String sql,Object... params){
        List<Map<String,Object>> result;
        try {
            //Connection conn = getConnection();
            result = QUERY_RUNNER.query(sql,new MapListHandler(),params);
        }catch (Exception e){
            logger.error("execute query failure",e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 插入实体
     * @param entityClass
     * @param fieldMap
     * @param <T>
     * @return
     */
    public static <T> boolean  insertEntity(Class<T> entityClass,Map<String,Object> fieldMap){
        if(CollectionUtil.isEmpty(fieldMap)){
            logger.error("can not insert entity: fieldMap is empty");
            return false;
        }

        String sql = "INSERT INTO "+getTableName(entityClass);
        StringBuilder columns = new StringBuilder("(");
        StringBuilder values = new StringBuilder(" VALUES(");
        for(String key:fieldMap.keySet()){
            columns.append(key+",");
            values.append("?,");
        }
        columns.replace(columns.lastIndexOf(","),columns.length(),")");
        values.replace(values.lastIndexOf(","),values.length(),")");
        sql = sql + columns +values;

        Object[]  params = fieldMap.values().toArray();
        return executeUpdate(sql,params) == 1;
    }


    /**
     * 更新实体
     * @param entityClass
     * @param id
     * @param fieldMap
     * @param <T>
     * @return
     */
    public static <T> boolean updateEntity(Class<T> entityClass,long id,Map<String,Object> fieldMap){
        if(CollectionUtil.isEmpty(fieldMap)){
            logger.error("can not update entity: fieldMap is empty");
            return false;
        }
        String updateSQL = "UPDATE "+getTableName(entityClass)+" SET ";
        StringBuilder columns = new StringBuilder();
        for(String key:fieldMap.keySet()){
            columns.append(key+"=?,");
        }
        columns.replace(columns.lastIndexOf(","),columns.length(),"");
        columns.append(" WHERE id="+id);
        updateSQL = updateSQL + columns;
        Object[] params = fieldMap.values().toArray();
        return executeUpdate(updateSQL,params) == 1;

    }

    /**
     * 删除实体
     * @param entityClass
     * @param id
     * @param <T>
     * @return
     */
    public static <T> boolean deleteEntity(Class<T> entityClass,long id){
        String sql = "DELETE FROM "+getTableName(entityClass)+" WHERE id=" + CastUtil.castString(id);
        int result = executeUpdate(sql);
        return result == 1;

    }

    /**
     * 执行更新语句
     * @param sql
     * @param params
     * @return
     */
    public static int executeUpdate(String sql,Object... params){
        int rows = 0;
        try {
            //Connection conn = getConnection();
            rows = QUERY_RUNNER.update(sql, params);
        }catch (SQLException e){
            logger.error("update sql failure",e);
            throw new RuntimeException(e);
        }finally {
            //closeConnection();
        }
        return rows;
    }

    /**
     * 根据SQL文件执行
     * @param filePath
     * @throws IOException
     */
    public static void executeSqlFile(String filePath) throws IOException {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String sql;
        while ((sql = reader.readLine()) != null){
            DatabaseHelper.executeUpdate(sql);
        }
    }


    private static <T> String getTableName(Class<T> entityClass) {
        return entityClass.getSimpleName();
    }

}
